package com.example.guli.service.base.handler;

import com.example.guli.common.base.result.R;
import com.example.guli.common.base.result.ResultCodeEnum;
import com.example.guli.service.base.exception.ExceptionUtils;
import com.example.guli.service.base.exception.GuliException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;



/**
 * 统一异常处理器
 * **/

@ControllerAdvice//切面，处理错误信息
@Slf4j//日志记录错误信息
public class GlobalExceptionHandler {
    //异常处理器
    @ExceptionHandler(Exception.class)
    @ResponseBody//返回json数据
    //通用异常捕获
    public R error(Exception e){
        e.printStackTrace();//错误跟踪站
        log.error(e.getMessage());//错误信息
        //将错误日志信息写入本地文件
        log.error(ExceptionUtils.getMessage(e));
        return R.error();
    }

    //数据重复
    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public R error(DuplicateKeyException e){
//        e.printStackTrace();
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCodeEnum.BAD_SQL_ZF);
    }

    //参数不正确
    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseBody
    public R error(DataIntegrityViolationException e){
//        e.printStackTrace();
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCodeEnum.PARAM_ERROR);
    }

    //sql语法错误
    @ExceptionHandler(BadSqlGrammarException.class)
    @ResponseBody
    public R error(BadSqlGrammarException e){
//        e.printStackTrace();
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);
    }

    //json解析异常
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public R error(HttpMessageNotReadableException e){
//        e.printStackTrace();
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCodeEnum.JSON_PARSE_ERROR);
    }



    //上传图片自定义(GuliException)异常捕获
    @ExceptionHandler(GuliException.class)
    @ResponseBody
    public R error(GuliException e){
//        e.printStackTrace();
        log.error(ExceptionUtils.getMessage(e));
        return R.error().message(e.getMessage()).code(e.getCode());
    }


}
